
import sys
import os

import json
import paho.mqtt.client as mqtt
import logging
from waveshare_epd import epd2in9_V2
from PIL import Image,ImageDraw,ImageFont

picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
logging.basicConfig(level=logging.DEBUG)

try:
    logging.info("epd demo")
    epd = epd2in9_V2.EPD()
    logging.info("init and clear")
    epd.init()
    

    font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)

except IOError as e:
    logging.info(e)
except KeyboardInterrupt:
    logging.info("ctrl+C:")
    epd2in9_V2.epdconfig.module_exit(cleanup=True)
    exit()
    

# MQTT Configurations
MQTT_SERVER = "d.xjton.cn"
MQTT_PORT = 1883
MQTT_TOPIC = "epd/control"

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(MQTT_TOPIC)

def on_message(client, userdata, msg):
    try:
        message = json.loads(msg.payload.decode())
        if 'command' in message:
            command = message['command']
            if command == 'clear':
                epd.Clear(0xFF)
                print("EPD clear")
            else:
                print("Unknown command:", command)
        else:
            print("No command field found in the message.")
    except Exception as e:
        print("Error processing message:", str(e))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(MQTT_SERVER, MQTT_PORT, 60)

try:
    client.loop_forever()
except KeyboardInterrupt:
    print("Exiting...")
